package com.mochasoft.shangchm.stop;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;

public class StopFilter implements Filter {
	private Set stopNumberSet;
		
	private String numbers;
	
	public StopFilter(){
		
	}
	public StopFilter(String numbers){
		stopNumberSet = new HashSet();
		if(numbers == null){
			this.numbers = "";
		}else{
			this.numbers = numbers;
		}
		StringTokenizer token = new StringTokenizer(this.numbers);	
		while(token.hasMoreElements()){
			String number = (String)token.nextElement();
			stopNumberSet.add(new Integer(number));
		}
	}
	public StopFilter(String[] numbers){
		stopNumberSet = makeStopSet(numbers);
	}
	
	public StopFilter(File file) throws IOException{
		stopNumberSet = makeStopSet(file);
	}
	
    public StopFilter(Reader reader) throws IOException{
    	stopNumberSet = makeStopSet(reader);
	}
	public Set getStopNumbers() {
		return stopNumberSet;
	}
	
	public static final Set makeStopSet(String[] stopNumbers) {
	    HashSet stopTable = new HashSet(stopNumbers.length);
	    for (int i = 0; i < stopNumbers.length; i++)
	      stopTable.add( new Integer(stopNumbers[i]));
	    return stopTable;
	  } 
	
	public static final Set makeStopSet(File wordfile)throws IOException{
		HashSet result = new HashSet();
	    FileReader reader = null;
	    try {
	      reader = new FileReader(wordfile);
	      result = (HashSet) makeStopSet(reader);
	    }
	    finally {
	      if (reader != null)
	        reader.close();
	    }
	    return result;
	}
	
   public static final Set makeStopSet(Reader reader) throws IOException{
	   HashSet result = new HashSet();
	    BufferedReader br = null;
	    try {
	      if (reader instanceof BufferedReader) {
	        br = (BufferedReader) reader;
	      } else {
	        br = new BufferedReader(reader);
	      }
	      String word = null;
	      while ((word = br.readLine()) != null) {
	    	 StringTokenizer token = new StringTokenizer(word);
	    	 while(token.hasMoreElements()){
	    		 result.add(new Integer((String)token.nextElement()));
	    	 }  
	      }
	    }
	    finally {
	      if (br != null)
	        br.close();
	    }
	    return result;
	}
}
